#include <iostream>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex;
pthread_cond_t cond;

void *Routine1(void *args)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_signal(&cond);
        std::cout << "我是线程A" << std::endl;
        pthread_cond_wait(&cond, &mutex);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    return nullptr;
}

void *Routine2(void *args)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_signal(&cond);
        std::cout << "我是线程B" << std::endl;
        pthread_cond_wait(&cond, &mutex);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }

    return nullptr;
}

int main()
{
    pthread_t p1, p2;

    pthread_mutex_init(&mutex, nullptr);
    pthread_cond_init(&cond, nullptr);
    pthread_create(&p1, nullptr, Routine1, nullptr);
    pthread_create(&p2, nullptr, Routine2, nullptr);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);

    return 0;
}